package example.documentbased.mainModule.mediators
{
	import example.documentbased.mainModule.controller.IMainController;
	import example.documentbased.mainModule.mediations.EditorsFacade;
	import example.documentbased.mainModule.models.MainModel;
	import example.documentbased.mainModule.models.vo.EditorVO;
	import example.documentbased.mainModule.views.IMainModuleViewContract;
	
	import mx.collections.ArrayList;
	import mx.managers.CursorManager;
	
	import org.etherframework.common.utils.OU;
	import org.etherframework.controller.events.CommandProcessingEvent;
	import org.etherframework.mediator.Mediator;
	
	public class MainModuleViewMediator extends Mediator implements IMainModuleViewContract
	{
		private var _model:MainModel;
		private var _editors:ArrayList = new ArrayList();
		private var _mainController:IMainController;
		private var _editorsFacade:EditorsFacade;
		
		public function MainModuleViewMediator(model:MainModel, mainController:IMainController, 
											   editorsFacade:EditorsFacade) 
		{
			_model = model;
			_mainController = mainController;
			_editorsFacade = editorsFacade;
		}

		override public function complete():void
		{
			ether.mediations.bind.property(_model.editors, mEditorsHandler);
			ether.mediations.bind.property(_model.lastUpdatedEditor, mLastUpdatedEditorHandler);
			
			ether.listen(CommandProcessingEvent.START, startProcessingHandler);
			ether.listen(CommandProcessingEvent.STOP, endProcessingHandler);
			
			_mainController.getStartupCommand().execute();
		}
		
		private function mLastUpdatedEditorHandler(editor:EditorVO):void
		{
			var editorVO:EditorVO = OU.getItem(editors, "id", editor.id) as EditorVO;
			
			if (editorVO)
			{
				editors.itemUpdated(editorVO);
			}
		}
		
		private function mEditorsHandler(items:ArrayList):void
		{
			editors = items;
		}
		
		private function startProcessingHandler(event:CommandProcessingEvent):void
		{
			CursorManager.setBusyCursor();
		}
		
		private function endProcessingHandler(event:CommandProcessingEvent):void
		{
			CursorManager.removeBusyCursor();
		}
		
		[Bindable]
		public function get editors():ArrayList { return _editors; }
		public function set editors(value:ArrayList):void { _editors = value; }
	}
}